// ==UserScript==
// @name         途家图片详情页面批量下载
// @namespace    http://tampermonkey.net/
// @version      v1.0.0.20250423
// @description  途家H5，图片详情页面，图片批量下载
// @author       Anderson
// @match        https://m.tujia.com/tbnb/detailImageList?unitId=*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=tujia.com
// @grant        GM_addStyle
// @require      https://unpkg.com/ajax-hook@2.0.3/dist/ajaxhook.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js
// @updateURL         https://gitee.com/anders5498/tampermonkey_script/edit/master/%E9%80%94%E5%AE%B6%E5%9B%BE%E7%89%87%E8%AF%A6%E6%83%85%E9%A1%B5%E9%9D%A2%E6%89%B9%E9%87%8F%E4%B8%8B%E8%BD%BD.user.js
// @downloadURL       https://gitee.com/anders5498/tampermonkey_script/edit/master/%E9%80%94%E5%AE%B6%E5%9B%BE%E7%89%87%E8%AF%A6%E6%83%85%E9%A1%B5%E9%9D%A2%E6%89%B9%E9%87%8F%E4%B8%8B%E8%BD%BD.user.js
// ==/UserScript==

(function () {
    'use strict';
    // 添加必要的CSS样式
    GM_addStyle(`
        .img-checkbox {
            margin-left: 10px;
            vertical-align: middle;
        }
    `);


    // 定义目标URL前缀
    const TARGET_PREFIX = 'https://m.tujia.com/bnbapp-node-h5/h5/house/gethouse/v3/bnb?refPid=';
    const IMAGE_HOST = 'https://pic.tujia.com';
    const GD_LOCATION = 'https://restapi.amap.com/v3/geocode/regeo?key=602951d65739a456ecf65def99752f77&location='
    let HOUSE_Id
    let imageList
    let cityName
    const { unProxy } = ah.proxy({
        onRequest: (config, handler) => {
            console.log(config)
            handler.next(config);
        },
        onResponse: (response, handler) => {
            if (response.config.url.startsWith(TARGET_PREFIX)) {
                let res = JSON.parse(response.response);
                console.log(res)
                HOUSE_Id = res.data.houseId
                imageList = res.data.mainPart.topModule.housePicture.housePics
                console.log(imageList)
                // 定位
                if (!res.data.mainPart.topModule.navigation.longitude || !res.data.mainPart.topModule.navigation.latitude) {
                    cityName = res.data.mainPart.topModule.navigation.title
                } else {
                    $.get({
                        url: `${GD_LOCATION}${res.data.mainPart.topModule.navigation.longitude},${res.data.mainPart.topModule.navigation.latitude}`,
                        type: 'get',
                        dataType: 'json',
                        success(locationRes) {
                            cityName = locationRes.regeocode.addressComponent.city
                            console.log(locationRes.regeocode.addressComponent)
                        }
                    })
                }
                console.log(cityName)
            }
            handler.next(response);
        }
    });
    // 页面卸载时解除拦截
    window.addEventListener('beforeunload', () => {
        unProxy();
    });
    // 插入元素
    setTimeout(() => {
        // 使用jQuery添加复选框
        $('div.cont-img-box').each(function (index) {
            const $checkbox = $('<input>', {
                type: 'checkbox',
                class: 'img-checkbox'
            });

            // 插入到目标元素之后
            $checkbox.insertAfter($(this));

            // 绑定点击事件
            $checkbox.on('click', function (e) {
                const isChecked = $(this).prop('checked');

                // 这里可以添加自定义逻辑
                const targetDiv = $(this).prev('.cont-img-box');
                if (isChecked) {
                    targetDiv.css('border', '1px solid red');
                } else {
                    targetDiv.css('border', '');
                }
            });
        });
    }, 2000)
    // 创建并配置按钮
    const $button = $('<button>', {
        id: 'topRightBtn',
        text: '下载',
        css: {
            'position': 'fixed',
            'right': '20px',
            'top': '20px',
            'width': '40px',
            'height': '30px',
            'opacity': '0.4',
            'background': '#4CAF50',
            'color': 'white',
            'border': 'none',
            'cursor': 'pointer',
            'z-index': 9999
        },
        click: function () {
            let houseId = location.href.replace('https://m.tujia.com/tbnb/detailImageList?unitId=', '').split('&')[0]
            console.log('即将执行批量下载！' + houseId);
            let imgCheckboxList = $('input.img-checkbox:checked')
            imgCheckboxList.each((index, item) => {
                setTimeout(() => {
                    let src = $(item).prev('.cont-img-box').find('img').data('src')
                    src = src.replace('/thumb', '')
                    let arr = src.split('/')
                    let filename = arr.pop()
                    let arr2 = filename.split('_.webp')[0].split('_')
                    let arr3 = arr2[arr2.length - 1].split('.')
                    arr.push(arr2[0] + '.' + arr3[arr3.length - 1])
                    src = arr.join('/')
                    downloadImageWithFetch(src, `${houseId}_${index * 1 + 1}`);
                }, index * 200)
            })
            // for (let index in imageList) {
            //     setTimeout(() => {
            //         const src = IMAGE_HOST + imageList[index].originUrl;
            //         // 跳过无src的元素
            //         if (!src) return;

            //         const fileName = `${cityName}_${HOUSE_Id}_${index * 1 + 1}`

            //         // 下载图片（处理跨域问题）
            //         downloadImageWithFetch(src, fileName);
            //     }, index * 200)
            // }
        }
    });
    // 插入到页面
    $('body').prepend($button);

    function downloadImageWithFetch(src, fileName) {
        console.log(src, fileName)

        fetch(src, { mode: 'cors' })
            .then(response => {
                if (!response.ok) throw new Error('网络错误');
                return response.blob();
            })
            .then(blob => {
                const downloadUrl = URL.createObjectURL(blob);
                const $a = $('<a>', {
                    href: downloadUrl,
                    download: fileName || 'downloaded_image'
                });
                $('body').append($a);
                $a[0].click();
                $a.remove();
                URL.revokeObjectURL(downloadUrl);
            })
            .catch(error => {
                console.error('下载失败:', error);
            });
    }
})();